package com.niyue.sandbox.uclock.clockr;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import org.apache.log4j.Logger;

public class LoadingSplash extends JFrame implements StatusSubscriber{
	private static final Logger logger = Logger.getLogger(StatusSubscriber.class);
	private static final long serialVersionUID = 1L;
	private JProgressBar jProgressBar = null;
	private JLabel jLabel = null;
	private FlickrDigitPool flickrDigitPool;  //  @jve:decl-index=0:
	private int maxPhoto=100;
	private ImagePanel splashPanel = null;
	public ImagePanel getSplashPanel() {
		if (splashPanel==null) {
			splashPanel=new ImagePanel();
			splashPanel.setLayout(null);
		}
		return splashPanel;
	}
	public FlickrDigitPool getFlickrDigitPool() {
		return flickrDigitPool;
	}
	public void setFlickrDigitPool(FlickrDigitPool flickrDigitPool) {
		this.flickrDigitPool = flickrDigitPool;
	}
	/**
	 * @param owner
	 */
	public LoadingSplash() {
		initialize();
	}
	public void loadPhotos(){
		assert(null != flickrDigitPool);
		this.setVisible(true);
		flickrDigitPool.setStatusSubscriber(this);		
		flickrDigitPool.initialize();
	}
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		jLabel = new JLabel();
		jLabel.setText("Loading photos: 0/100");
		this.add(getSplashPanel(),BorderLayout.NORTH);
		this.add(getJProgressBar(), BorderLayout.CENTER);
		this.add(jLabel, BorderLayout.SOUTH);
		Dimension screenSize =
	          Toolkit.getDefaultToolkit().getScreenSize();
		 Dimension labelSize = jLabel.getPreferredSize();
		 setLocation(screenSize.width/2 - (labelSize.width/2),
                 screenSize.height/2 - (labelSize.height/2));
		 ImagePanel splashPanel = getSplashPanel();
		 InputStream inputStream=LoadingSplash.class.getResourceAsStream("splash.png");
		 BufferedImage image;
		try {
			image = ImageIO.read(inputStream);
			splashPanel.setImage(image);
			this.setSize(image.getWidth(), image.getHeight()+labelSize.height+10);
		} catch (IOException e) {
			logger.error("Oops, splash screen can not be correctly loaded. "+e.getMessage());
		}
	}

	/**
	 * This method initializes jProgressBar	
	 * 	
	 * @return javax.swing.JProgressBar	
	 */
	private JProgressBar getJProgressBar() {
		if (jProgressBar == null) {
			jProgressBar = new JProgressBar(JProgressBar.HORIZONTAL,maxPhoto);
		}
		return jProgressBar;
	}
	
	public void update(int photosLoaded) {
		jLabel.setText("Loading photos: "+photosLoaded+"/"+maxPhoto);
		jProgressBar.setValue(photosLoaded);
	}
}
